package com.itheima.pool.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DuridPoolUtils {
    private DuridPoolUtils() {
    }

    private static DataSource dataPool;

    static {
        InputStream is = DuridPoolUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        Properties p = new Properties();
        try {
            p.load(is);
            dataPool = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection con = dataPool.getConnection();
        return con;
    }

    //提供一个获取数据库连接池对象的方法
    public static DataSource getDataSource() {
        return dataPool;
    }

    //关闭资源

    public static void close(Connection con, PreparedStatement pst, ResultSet rs) throws SQLException {
        if (con != null) {
            con.close();
        }
        if ( pst != null) {
            pst.close();
        }
        if (rs != null) {
            rs.close();
        }
    }
    public static void close(Connection con, PreparedStatement pst) throws SQLException {
        close(con,pst,null);
    }
}
